<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @drag-sort="sortTable"
    >
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="handleCreateEvent">创建执行语句</el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="CircleClose" @click="handleCloseTask(scope)">关闭</el-button>
      </template>
    </ProTable>
    <!-- 创建执行参数 -->
    <el-dialog v-model="dialogVisible" title="创建Sqlite语句" width="800" :align-center="true">
      <div style="max-height: 500px; overflow: auto">
        <el-form ref="ruleFormRef" :rules="rules" :model="formData" label-width="140px">
          <el-form-item label="语句类型 :" prop="sentence_type">
            <el-radio-group v-model="formData.sentence_type">
              <el-radio :value="1">查询</el-radio>
              <el-radio :value="2">执行</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="店铺ID :" prop="shop_id">
            <el-input v-model="formData.shop_id" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="设备ID :" prop="device_id">
            <el-input v-model="formData.device_id" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="执行语句 :" prop="sentence">
            <el-input v-model="formData.sentence" type="textarea" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="启动时间[时间戳] :" prop="start_time">
            <el-input v-model="formData.start_time" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="备注 :" prop="remark">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="动态密码 :" prop="password">
            <el-input v-model="formData.password" type="textarea" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleCreateSentece(ruleFormRef)"> 创建 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import { User } from "@/api/interface";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { getOrderList } from "@/api/modules/datawarn";
import ShowChileDate from "@/components/ShowChileDate/index.vue";
import { CirclePlus, CircleClose } from "@element-plus/icons-vue";
dayjs.extend(utc);
dayjs.extend(timezone);
// ProTable 实例
const dialogVisible = ref(false);
const ruleFormRef: any = ref<FormInstance>();
const proTable = ref<ProTableInstance>();
const formData = reactive({
  sentence_type: 1, // 1
  sentence: "",
  start_time: "",
  shop_id: "",
  device_id: "",
  remark: "",
  password: ""
});
const rules = reactive<FormRules>({
  sentence_type: [{ required: true, message: "该字段必填", trigger: "blur" }],
  sentence: [{ required: true, message: "该字段必填", trigger: "change" }],
  start_time: [{ required: true, message: "该字段必填", trigger: "change" }],
  shop_id: [{ required: true, message: "该字段必填", trigger: "change" }],
  device_id: [{ required: true, message: "该字段必填", trigger: "change" }],
  remark: [{ required: true, message: "该字段必填", trigger: "change" }]
});
// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  pageNum: 1,
  pageSize: 10
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.list,
    total: data.total
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  let startTime: any = undefined;
  let endTime: any = undefined;
  if (newParams.created_at) {
    startTime = dayjs.tz(newParams.created_at, "America/Santiago").startOf("day").unix();
    endTime = dayjs.tz(newParams.created_at, "America/Santiago").endOf("day").utc().unix();
    delete newParams.created_at;
  }
  const pageParams = {
    is_exchange: newParams.is_exchange,
    type: newParams.type,
    start_time: startTime,
    end_time: endTime,
    limit: newParams.pageSize,
    page: newParams.pageNum
  };
  return getOrderList(pageParams);
};
const handleCreateEvent = () => {
  dialogVisible.value = true;
};
const handleCloseTask = (scope: any) => {
  console.log(scope.row);
};
// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  { prop: "id", label: "ID", width: 80 },
  {
    prop: "shop_id",
    label: "店铺ID",
    width: 100
  },
  {
    prop: "id",
    label: "设备ID",
    width: 200
  },
  {
    prop: "type",
    label: "类型",
    width: 100
  },
  {
    prop: "id",
    label: "执行语句",
    width: 100
  },
  {
    prop: "out_trade_no",
    label: "执行状态",
    width: 150,
    render: () => {
      return <el-tag type="info">待执行</el-tag>;
    }
  },
  {
    prop: "file_path",
    label: "执行结果",
    width: 100,
    render: () => {
      return "{total: 200}";
    }
  },
  {
    prop: "os_info",
    width: 180,
    label: "执行附带参数"
  },
  {
    prop: "remark",
    label: "备注"
  },
  {
    prop: "start_time",
    label: "执行开始日期",
    width: 180,
    render: (scope: any) => {
      return <ShowChileDate value={scope.row.order_create_time} />;
    }
  },
  {
    prop: "created_at",
    label: "执行结束日期",
    width: 180,
    render: (scope: any) => {
      return <ShowChileDate value={scope.row.order_create_time} />;
    }
  },
  {
    prop: "created_at",
    label: "创建日期",
    width: 180,
    render: (scope: any) => {
      return <ShowChileDate value={scope.row.order_create_time} />;
    }
  },
  { prop: "operation", label: "操作", fixed: "left", width: 100 }
]);

const handleCreateSentece = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return;
  }
  await formEl.validate();
  console.log(formData);
};

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};
</script>

<style scoped>
.order-container {
  padding: 12px;
  margin-bottom: 20px;
  border-radius: 4px;
}
.positive-order {
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
}
.negative-order {
  background-color: #fef0f0;
  border: 1px solid #fde2e2;
}
.order-title {
  margin-bottom: 10px;
  font-weight: bold;
  color: #333333;
}
.goods-item {
  padding: 8px 0;
  border-bottom: 1px dashed #ebeef5;
}
.goods-item:last-child {
  border-bottom: none;
}
.goods-name {
  margin-bottom: 4px;
  color: #606266;
}
.goods-price {
  font-size: 13px;
  color: #909399;
}
</style>
